﻿// plotlyInterop.js - 支持多个矩形Shape的版本

const plotlyManager = {
    chart: null,
    container: null,
    isLoaded: false,
    shapes: [], // 存储所有矩形Shape

    // 初始化Plotly.js
    init: async function () {
        if (this.isLoaded) return true;

        if (typeof Plotly !== 'undefined') {
            this.isLoaded = true;
            return true;
        }

        return new Promise((resolve) => {
            const script = document.createElement('script');
            script.src = 'https://cdn.plot.ly/plotly-2.24.1.min.js';
            script.onload = () => {
                this.isLoaded = true;
                console.log('Plotly.js加载成功');
                resolve(true);
            };
            script.onerror = () => {
                console.error('Plotly.js加载失败');
                resolve(false);
            };
            document.head.appendChild(script);
        });
    },

    // 创建图表
    createChart: async function (containerId, xData, yData, dotNetHelper) {
        if (!await this.init()) return false;

        this.container = document.getElementById(containerId);
        if (!this.container) {
            console.error(`找不到容器元素: ${containerId}`);
            return false;
        }

        // 清除现有图表
        if (this.chart) {
            Plotly.purge(this.container);
            this.shapes = []; // 清空存储的shapes
        }

        try {
            const trace = {
                x: xData,
                y: yData,
                type: 'scatter',
                mode: 'lines',
                line: { color: '#4285F4', width: 2 }
            };

            const layout = {
                title: '可拖拽矩形选择区域的折线图',
                dragmode: 'select',
                selectdirection: 'h',
                margin: { t: 40, b: 40, l: 60, r: 40 },
                xaxis: { title: 'X轴' },
                yaxis: { title: 'Y轴' },
                shapes: this.shapes // 初始化时使用存储的shapes
            };

            this.chart = await Plotly.newPlot(this.container, [trace], layout);
            this.setupEvents(dotNetHelper);
            return true;
        } catch (error) {
            console.error('创建图表失败:', error);
            return false;
        }
    },

    // 设置事件监听
    setupEvents: function (dotNetHelper) {
        if (!this.container) return;

        // 双击事件 - 添加新矩形
        this.container.on('plotly_doubleclick', () => {
            this.addNewSelectionRect(0, 10); // 默认添加一个小矩形
            dotNetHelper.invokeMethodAsync('OnShapeAdded');
        });

        // 选择事件
        this.container.on('plotly_selected', (e) => {
            if (e?.range?.x) {
                const [x0, x1] = e.range.x;
                this.addNewSelectionRect(x0, x1);
                dotNetHelper.invokeMethodAsync('OnShapeAdded', x0, x1);
            }
        });
    },

    // 添加新的选择矩形
    addNewSelectionRect: function (x0, x1) {
        if (!this.container) return;

        // 确保坐标有效
        if (typeof x0 !== 'number' || typeof x1 !== 'number') return;

        // 确保x0 < x1
        if (x0 > x1) [x0, x1] = [x1, x0];

        // 创建新矩形
        const newRect = {
            type: 'rect',
            xref: 'x',
            yref: 'paper',
            x0: x0,
            y0: 0,
            x1: x1,
            y1: 1,
            fillcolor: this.getRandomColor(),
            line: {
                color: '#000',
                width: 1
            },
            opacity: 0.5
        };

        // 添加到shapes数组
        this.shapes.push(newRect);

        // 更新图表
        Plotly.relayout(this.container, {
            shapes: this.shapes
        });
    },

    // 生成随机颜色
    getRandomColor: function () {
        const colors = [
            'rgba(255, 99, 132, 0.5)',
            'rgba(54, 162, 235, 0.5)',
            'rgba(255, 206, 86, 0.5)',
            'rgba(75, 192, 192, 0.5)',
            'rgba(153, 102, 255, 0.5)'
        ];
        return colors[Math.floor(Math.random() * colors.length)];
    },

    // 清除所有选择
    clearAllSelections: function () {
        if (!this.container) return;

        this.shapes = []; // 清空数组
        Plotly.relayout(this.container, {
            shapes: []
        });
    },

    // 获取当前所有shapes
    getCurrentShapes: function () {
        return this.shapes;
    },

    // 删除最后一个shape
    removeLastShape: function () {
        if (!this.container || this.shapes.length === 0) return;

        this.shapes.pop(); // 移除最后一个
        Plotly.relayout(this.container, {
            shapes: this.shapes
        });
    }
};

// 导出接口
window.plotlyInterop = {
    initialize: (containerId, xData, yData, dotNetHelper) =>
        plotlyManager.createChart(containerId, xData, yData, dotNetHelper),
    addSelectionRect: (x0, x1) => plotlyManager.addNewSelectionRect(x0, x1),
    clearAllSelections: () => plotlyManager.clearAllSelections(),
    getCurrentShapes: () => plotlyManager.getCurrentShapes(),
    removeLastShape: () => plotlyManager.removeLastShape()
};

// 预加载Plotly.js
plotlyManager.init();